package com.keepc.licence.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.keepc.licence.entity.AdditionInfo;
import com.keepc.licence.entity.LicenseCreatorParam;
import com.keepc.licence.serverinfo.AbstractServerInfos;
import com.keepc.licence.serverinfo.LinuxServerInfos;
import com.keepc.licence.serverinfo.WindowsServerInfos;
import com.keepc.licence.util.LicenseCreator;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 证书生成控制器
 */
@RestController
@Api(tags = "license证书")
@RequestMapping("/license")
public class LicenseController {

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    @ApiOperation("获取服务器硬件信息")
    @GetMapping("/getServerInfos/{osName}")
    public AdditionInfo getServerInfos(
            @ApiParam(name = "osName", value = "系统类型 windows / linux", required = true) @PathVariable String osName) {
        // 操作系统类型
        if (StringUtils.isBlank(osName)) {
            osName = System.getProperty("os.name");
        }
        osName = osName.toLowerCase();

        AbstractServerInfos abstractServerInfos;

        // 根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        } else {// 其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }

        return abstractServerInfos.getServerInfos();
    }

    @ApiOperation("生成证书")
    @PostMapping("/generateLicense")
    public Map<String, Object> generateLicense(@RequestBody LicenseCreatorParam param) {
        Map<String, Object> resultMap = new HashMap<>(2);
        if (StringUtils.isBlank(param.getLicensePath())) {
            param.setLicensePath(licensePath);
        }
        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();
        if (result) {
            resultMap.put("code", "200");
            resultMap.put("msg", param);
        } else {
            resultMap.put("code", "401");
            resultMap.put("msg", "证书文件生成失败！");
        }
        return resultMap;
    }
}